﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CanDichVu.Db;
using CanDichVu.Service.Iservice;
using CanDichVu.Db.Entity;

namespace CanDichVu.Service.Vervices
{
    public class QuanHuyenSer : IQuanHuyen
    {
        private readonly EntitiesCanDichVu dbContext = new EntitiesCanDichVu();

        public int addorUpdate(Db.QuanHuyen entity)
        {
            try
            {
                dbContext.Entry(entity).State = entity.Id == 0 ? System.Data.EntityState.Added : System.Data.EntityState.Modified;
                dbContext.SaveChanges();
                return entity.Id;
            }
            catch
            {
                return 0;
            }
        }

        public List<Db.QuanHuyen> getList(int cateid)
        {
            try
            {
                return dbContext.QuanHuyens.Where(p => p.TinhthanhId == cateid || cateid == 0).ToList();
            }
            catch
            {
                return null;
            }
        }

        public Db.QuanHuyen GetById(int id)
        {
            try
            {
                return dbContext.QuanHuyens.Where(p => p.Id == id).First();
            }
            catch { return null; }
        }

        public bool detele(int id)
        {
            try
            {
                var _entity = GetById(id);
                dbContext.QuanHuyens.Remove(_entity);
                dbContext.SaveChanges();
                return true;
            }
            catch { return false; }
        }

        public List<ListEntityDorpList> ListCateAllDorp(int nhomcha)
        {
            List<ListEntityDorpList> ListRetuen = new List<ListEntityDorpList>();

            var listArrayCateId = dbContext.QuanHuyens.Where(p => p.TinhthanhId == nhomcha).ToList();

            foreach (var i in listArrayCateId)
            {
                ListEntityDorpList ml = new ListEntityDorpList();
                ml.id = i.Id;
                ml.text = i.Name;
                ml.children = new List<ListEntityDorpList>();
                //var _list = ListCateAllDorp(i.Id);
                //ml.children.AddRange(_list);

                ListRetuen.Add(ml);

            }

            return ListRetuen;
        }
    }
}
